<template>
  <Echart v-if="data.length" :options="options"></Echart>
  <el-empty v-else description="暂无数据" />
</template>

<script setup>
import Echart from '@/components/Echart/index'
import { generateTimeArray } from '@/utils/index'

const props = defineProps({
  data: {
    type: Object,
    default: () => ([]),
  },
  option: {
    type: Object,
    default: () => ({})
  },
})

const options = ref({
  dataset: {
    source: props.data // 直接使用原始数据
  },
  tooltip: {
    trigger: 'axis',
  },
  grid: {
    right: "15",
    bottom: "0",
    top: "30",
    left: "10",
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: generateTimeArray(),
    axisTick: {
      show:false,
    },
    axisLabel: {
      align: 'center',  // 关键设置：标签居中
      interval: function(index,value) {
        let arr = [3,6,9,12,15,18,21] // x轴坐标只返回3,6,9,12,15,18,21点
        if (arr.includes(parseInt(value.split(':')[0])) && value.endsWith(':00')) {
          return value;
        }
        return false;
      },
    },
  },
  yAxis: {
    name:'kW',
    nameTextStyle: {
      align: 'right',
    },
    type: 'value',
    splitLine: {
      lineStyle: {
        type: 'dashed', //虚线
      },
      show: true //隐藏
    },
  },
  series: [{
    type: 'line',
    itemStyle: { // 折现颜色
      color:'#679aff'
    },
    areaStyle: {
      opacity: 0.3
    },
    smooth: true,
    barWidth: "12", // 折现宽度
    symbolSize: 6, // 小圆点大小
    symbol: 'circle',
    encode: {
      x:'name',
      y:'value'
    }
  }]
})

// 折线图数据转换
function chartFormat(data,legendName) {
  let range = [0,1,2,21,22,23,24]
  let arr = JSON.parse(JSON.stringify(data))
  return arr.map(item => {
    if(legendName) {
      item.legendName = legendName
    }
    if(range.includes(parseInt(item.name.split(':')[0]))) {
      item.name = null
      item.value = null
    }
    return item
  })
}

watch(() => props.data, (val) => {
  options.value.dataset.source = chartFormat(val)
}, {
  deep: true
})
watch(() => props.option, (val) => {
  options.value = {...options.value,...val}
}, {
  deep: true,
  immediate: true
})
</script>

<style lang="less" scoped>
</style>